#!/usr/bin/env ruby
# :title: ShakeBook Pro
# 
# == About
# MacBook Pro Space Shaker
# Uses the MacBooks internal sudden motion sensor to switch your spaces.
# 
# Author:: Rob Hurring (mailto:rob@ubrio.us)
# Blog:: Blogubrious (http://blog.ubrio.us)
# Version:: 1.0
# Copyright:: Copyright (c) 2008 Ubrious.
# License:: Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
# 
# == Examples
# AMSTracker -s -u0.01 | shakebook.rb
#     
# == Credits & Thanks
# * Erling Ellingsen (http://blog.medallia.com) for the original idea and everything :)
# * Amit Singh for AMSTracker (http://www.osxbook.com/software/sms/amstracker)
# 
#--
# ToDo:
#   - make the smacking more sensitive, or start asking for donations for a new monitor
#++

# generates the applescript necessary to switch spaces
def goto(space)
`osascript<<EOS
    tell application "System Events"
    	tell process "Finder"
    		keystroke "#{space}" using control down
    	end tell
    end tell
EOS
`
end
stable = 0
while line = gets.chomp do
  axis = line.scan(/-?\d+/).map{ |i| i.to_i }
  next if axis.empty?
  axis[0] += 200 if axis[0] < 0
  x = axis[1] * 200 + axis[0]
  if x.abs < 20
    stable += 1
  end
  if x.abs > 30 and stable > 30
    stable = 0
    goto x < 0 ? 1 : 2
  end
end